package com.chu.cloud.rabbit.listener;

import com.chu.cloud.entity.ShoppingCart;
import com.chu.cloud.enums.CartEventType;
import com.chu.cloud.rabbit.RabbitConstants;
import com.chu.cloud.service.ShoppingCartService;
import com.chu.cloud.util.BeanUtil;
import com.chu.cloud.util.JsonUtils;
import com.chu.cloud.vo.ShoppingCartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/8/8 17:22
 * @Description:
 */
@RabbitListener(queues = RabbitConstants.FanoutQueueName.SHOPPING_CART_EVENT)
@Component
@Slf4j
public class ShoppingCartEventReceive {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @RabbitHandler
    public void receive(ShoppingCartVo cartVo) {
        log.info("收到购物车事件:{}", JsonUtils.obj2json(cartVo));
        CompletableFuture.runAsync(() -> {
            if (CartEventType.ADD_ITEM.equals(cartVo.getCartEvent())) {
                ShoppingCart shoppingCart = new ShoppingCart();
                BeanUtil.copyProperties(shoppingCart, cartVo, true);
                shoppingCartService.addCart(shoppingCart);
            }else {
                shoppingCartService.removeCartItem(cartVo.getId(),cartVo.getMemberId());
            }
        }).exceptionally(e ->{
            log.error("异常信息:",e);
            return null;
        });
    }
}
